using System;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using ErpManager.WPF.Models;

namespace ErpManager.WPF.Services
{
    public class AuthenticationService
    {
        private readonly ApplicationDbContext _context;
        private readonly LogService _logService;

        public AuthenticationService(ApplicationDbContext context)
        {
            _context = context;
            _logService = new LogService(context, "system", "系统");
        }

        public async Task<(bool success, string message)> RegisterAsync(string username, string password)
        {
            try
            {
                if (await _context.Users.AnyAsync(u => u.Username == username))
                {
                    return (false, "用户名已存在");
                }

                var passwordHash = BCrypt.Net.BCrypt.HashPassword(password);
                var user = new User
                {
                    Username = username,
                    PasswordHash = passwordHash,
                    CreateTime = DateTime.Now,
                    UpdateTime = DateTime.Now
                };

                _context.Users.Add(user);
                await _context.SaveChangesAsync();

                // 记录注册成功日志
                await _logService.LogOperationAsync("用户管理", "注册", $"新用户 {username} 注册成功");

                return (true, "注册成功");
            }
            catch (Exception ex)
            {
                return (false, $"注册失败: {ex.Message}");
            }
        }

        public async Task<(bool success, User? user, string message)> LoginAsync(string username, string password)
        {
            try
            {
                var user = await _context.Users.FirstOrDefaultAsync(u => u.Username == username);
                if (user == null)
                {
                    // 记录登录失败日志
                    await _logService.LogOperationAsync("用户管理", "登录", $"用户 {username} 登录失败：用户名不存在");
                    return (false, null, "用户名不存在");
                }

                if (!BCrypt.Net.BCrypt.Verify(password, user.PasswordHash))
                {
                    // 记录登录失败日志
                    await _logService.LogOperationAsync("用户管理", "登录", $"用户 {username} 登录失败：密码错误");
                    return (false, null, "密码错误");
                }

                user.LastLoginTime = DateTime.Now;
                user.UpdateTime = DateTime.Now;
                await _context.SaveChangesAsync();

                // 记录登录成功日志
                await _logService.LogOperationAsync("用户管理", "登录", $"用户 {username} 登录成功");

                return (true, user, "登录成功");
            }
            catch (Exception ex)
            {
                return (false, null, $"登录失败: {ex.Message}");
            }
        }
    }
}
